#include "stdafx.h"
#include "BoundingBox.h"

using namespace mmath;

BoundingBox::BoundingBox()
{
	Min = XMFLOAT3(0,0,0);
	Max = XMFLOAT3(0,0,0);
}

void BoundingBox::initWithSphere( XMVECTOR center, float radius )
{
	XMVECTOR radiusVec = XMVectorReplicate(radius);
	
	XMStoreFloat3(&Min, XMVectorSubtract(center, radiusVec));
	XMStoreFloat3(&Max, XMVectorAdd(center, radiusVec));
}

void BoundingBox::growBySphere( XMVECTOR center, float radius )
{
	XMVECTOR minC = XMLoadFloat3(&Min);
	XMVECTOR maxC = XMLoadFloat3(&Max);

	XMVECTOR radiusVec = XMVectorReplicate(radius);

	minC = XMVectorMin(minC, XMVectorSubtract(center, radiusVec));
	maxC = XMVectorMax(maxC, XMVectorAdd(center, radiusVec));

	XMStoreFloat3(&Min, minC);
	XMStoreFloat3(&Max, maxC);
}

void BoundingBox::scale( float s )
{
	XMVECTOR minC = XMLoadFloat3(&Min);
	XMVECTOR maxC = XMLoadFloat3(&Max);

	XMVECTOR minToMax = XMVectorSubtract(maxC, minC);

	XMVECTOR offsetLen = XMVectorReplicate( (1.0f - s) * 0.5f );
	minC = XMVectorMultiplyAdd( minToMax, offsetLen, minC);
	maxC = XMVectorMultiplyAdd(-minToMax, offsetLen, maxC);

	XMStoreFloat3(&Min, minC);
	XMStoreFloat3(&Max, maxC);
}

bool BoundingBox::isNonZero()
{
	return XMVector3Less( XMLoadFloat3(&Min), XMLoadFloat3(&Max) );
}

BoundingBox BoundingBox::maximum(const BoundingBox & b1, const BoundingBox & b2)
{
	XMVECTOR min1 = XMLoadFloat3(&b1.Min);
	XMVECTOR max1 = XMLoadFloat3(&b1.Max);

	XMVECTOR min2 = XMLoadFloat3(&b2.Min);
	XMVECTOR max2 = XMLoadFloat3(&b2.Max);

	XMVECTOR minNew = XMVectorMin(min1, min2);
	XMVECTOR maxNew = XMVectorMax(max1, max2);

	BoundingBox box;
	XMStoreFloat3(&box.Min, minNew);
	XMStoreFloat3(&box.Max, maxNew);
	return box;
}